package com.briup.estore.adminAPI.conf;

import com.alibaba.fastjson.JSON;
import com.briup.estore.common.exception.ShopCommonException;
import com.briup.estore.common.util.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author adam
 * @date 2023/5/15
 */
@ControllerAdvice
public class GlobalException {
    @ExceptionHandler
    public void resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        if (ex instanceof ShopCommonException) {

            ShopCommonException re = (ShopCommonException) ex;
            try {
                out = response.getWriter();
                Result result = Result.error(re.getCode(), re.getMessage());
                out.println(JSON.toJSON(result));

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            Result result = Result.error(50000, "服务器内部错误");
            out.println(JSON.toJSON(result));
            ex.printStackTrace();
        }
        out.flush();
        out.close();
    }

}
